<?php

class Controller_quality extends Template
{
    //分销直帐不良品状态
    protected $fxCheckMsg = array(
        '1'=>'描述不符',
        '2'=>'外观问题',
        '3'=>'功能问题',
        '4'=>'配件问题',
        '5'=>'尺寸不符',
        '6'=>'款型不符',
        '7'=>'脏污破损',
        '8'=>'其他不良',
    );
    /**
     *生成质检单，不合格处理的功能,且生成入库单
     */
    public function before()
    {
        try{
            ACL::Required('qc');
        }catch(HTTP_Exception_403 $e){
            Message::error('sorry，你没有权限进这个目录');
            $this->request->redirect(URL::base(TRUE));
        }
        include_once(MODPATH.'/common/logs.php');
        parent::before();

    }

    public function Action_index()
    {   
        $view = View::factory('quality/quality');
        $this->title        = "扫描质检";
        $batch_code = isset($_GET['batch_code']) ? addslashes(trim($_GET['batch_code'])) : '';
        $receiveDetailId = isset($_GET['receiveDetailId']) ? addslashes(trim($_GET['receiveDetailId'])) : '';
        $signSelect = isset($_GET['skuchecksignselected']) ? $_GET['skuchecksignselected'] : -1;

        if(empty($batch_code) && empty($receiveDetailId)) {
            if(count($_GET)>1){
                Message::error('请输入批次号或收货明细单号');
            }
        } else {
            $recieveDetailsTable = DB::select()
                ->from('recieve_invoices')
                ->join('recieve_details')
                ->on('recieve_invoices.id','=','recieve_details.recieve_invoice_id');
            $recieveDetailsTableSkuClone = DB::select()
                ->from('recieve_invoices')
                ->join('recieve_details')
                ->on('recieve_invoices.id','=','recieve_details.recieve_invoice_id');
            $recieveDetailsTablePuOrdClone = DB::select()
                ->from('recieve_invoices')
                ->join('recieve_details')
                ->on('recieve_invoices.id','=','recieve_details.recieve_invoice_id');

            if(!empty($receiveDetailId)) {
                $recieveDetailsTable->where('recieve_details.id', '=', $receiveDetailId);
                $recieveDetailsTableSkuClone->where('recieve_details.id', '=', $receiveDetailId);
                $recieveDetailsTablePuOrdClone->where('recieve_details.id', '=', $receiveDetailId);
            }

            if(!empty($batch_code)) {
                $recieveDetailsTable->where('recieve_details.batch_code', '=', $batch_code);
                $recieveDetailsTableSkuClone->where('recieve_details.batch_code', '=', $batch_code);
                $recieveDetailsTablePuOrdClone->where('recieve_details.batch_code', '=', $batch_code);
            }

            if($signSelect != -1) {
                $recieveDetailsTable->where('recieve_details.skuchecksign', '=', $signSelect);
                $recieveDetailsTableSkuClone->where('recieve_details.skuchecksign', '=', $signSelect);
                $recieveDetailsTablePuOrdClone->where('recieve_details.skuchecksign', '=', $signSelect);
            }

            $recieveDetailsTable->order_by('recieve_details.id', 'ASC');

            $recieveDetails = $recieveDetailsTable->execute('newerp')->as_array();

            if(empty($recieveDetails)) {
                if(!empty($batch_code)) {
                    if(!DB::select('id')->from('batches')
                        ->where('batch_code', '=', $batch_code)
                        ->execute('newerp')
                        ->get('id')
                    ) {
                        Message::error('批次号不存在');
                    } else {
                        Message::error('查询结果为空');
                    }
                }
                unset($recieveDetailsTableSkuClone, $recieveDetailsTable, $recieveDetailsTablePuOrdClone);
            } else {
                $logicNames = Kohana::$config->load('logic')->get('logics');
                $warehouse_id = $recieveDetails[0]['warehouseid'];
                $warehouse_location = '';
                $logics = Kohana::$config->load('logic')->get('logics');
                $logicTypes = array_keys($logics);
                $stores = Kohana::$config->load('vmi_warehouse')->as_array();

                $currentSkus = $recieveDetailsTableSkuClone
                    ->select(DB::expr('UPPER(recieve_details.sku) AS sku'))
                    ->group_by('sku')
                    ->execute('newerp')
                    ->as_array(NULL, 'sku');
                $currentPuOrdIds = $recieveDetailsTablePuOrdClone
                    ->select(DB::expr('recieve_details.id AS recieveDetailId'), 'recieve_invoices.purchaseorder_id')
                    ->execute('newerp')
                    ->as_array('recieveDetailId', 'purchaseorder_id');
                unset($recieveDetailsTableSkuClone, $recieveDetailsTable, $recieveDetailsTablePuOrdClone);

                $skuLogics = !empty($currentSkus) ? Skusystemapi::getSkuArrAttr($currentSkus) : array();
                $puOrdRemarks = !empty($currentPuOrdIds) ?
                    DB::select('id', 'remark')
                        ->from('purchaseorders')
                        ->where('id', 'in', array_unique($currentPuOrdIds))
                        ->execute('newerp')
                        ->as_array('id', 'remark') : array();
                $checkDetails = !empty($currentPuOrdIds) ?
                    DB::select('id', 'recieve_detail_id', 'qualified_quantity', 'check_quantity', 'unquality_count', 'remark')
                        ->from('check_quality_details')
                        ->where('recieve_detail_id', 'in', array_keys($currentPuOrdIds))
                        ->execute('newerp')
                        ->as_array('recieve_detail_id') : array();
                unset($currentSkus, $currentPuOrdIds);

                foreach ($recieveDetails as &$detail) {
                    $sql="SELECT `export_tax_rebate`
                              FROM `purchaseorders`
                              WHERE `id`=".$detail['purchaseorder_id'];
                    $export_tax_rebate=DB::query(Database::SELECT,$sql)->execute('newerp')->get('export_tax_rebate');
                    $detail['export_tax_rebate']=$export_tax_rebate;
                    $detail['puRemark'] = isset($puOrdRemarks[$detail['purchaseorder_id']]) ? $puOrdRemarks[$detail['purchaseorder_id']] : '';
                    $detail['storeName'] = ($detail['store'] == 0 ? $warehouse_location : (isset($stores[$detail['store']]) ? $stores[$detail['store']] : '未知仓库'));

                    if (isset($skuLogics[$detail['sku']]) && !empty($skuLogics[$detail['sku']]) && in_array($skuLogics[$detail['sku']], $logicTypes)) {
                        $detail['logicStr'] = sprintf('%03d#', $skuLogics[$detail['sku']]).$logicNames[$skuLogics[$detail['sku']]];
                        $detail['isSave'] = TRUE;
                    } else {
                        $detail['logicStr'] = '请选择属性';
                        $detail['isSave'] = FALSE;
                    }

                    $detail['xu_check'] = $detail['arrival_quantity'] - (isset($checkDetails[$detail['id']]['check_quantity']) ? $checkDetails[$detail['id']]['check_quantity'] : 0);
                    $detail['qualified_quantity'] = isset($checkDetails[$detail['id']]['qualified_quantity']) ? $checkDetails[$detail['id']]['qualified_quantity'] : 0;
                    $detail['unquality_count'] = isset($checkDetails[$detail['id']]['unquality_count']) ? $checkDetails[$detail['id']]['unquality_count'] : 0;
                    $detail['unquality_remark'] = isset($checkDetails[$detail['id']]['remark']) ? $checkDetails[$detail['id']]['remark'] : '';
                    $detail['checkId'] = isset($checkDetails[$detail['id']]) ? $checkDetails[$detail['id']]['id'] : 0;

                    $supplier = supplierskus::getSuppliers(array('name'), array('id' => "=" . $detail['supplier']));
                    $detail['suName'] = isset($supplier[0]['name']) ? $supplier[0]['name'] : '';
                    $detail['uids'] = DB::select()
                    ->from('check_quality_fx_msg')
                    ->where('recieve_detail_id', '=', $detail['id'])
                    ->execute('newerp')->get('badProType');
                }
                unset($skuLogics, $checkDetails, $supplier, $puOrdRemarks);
            }
            $view->bind('recieveDetails', $recieveDetails);
        }

        $view->set('batch_code', $batch_code)
            ->set('receiveDetailId', $receiveDetailId)
            ->set('skuchecksignselected', $signSelect)
            ->set('fxCheckMsg',$this->fxCheckMsg);

        $this->response->body($view);
    }


    /*批量质检*/
    public function Action_checkQuanlityMore() {
        $re = array();
        $checkDetailId = 0;//生成的质检单ID
        $checkTime = date('Y-m-d H:i:s',time());

        $recieveInvoiceInfos = $recieveDetailInfos = array();
        foreach($_POST['checkQuanlityDetails'] as $checkDetail) {
            $recieveInvoiceInfos[] = $checkDetail['recieve_invoice_id'];
            $recieveDetailInfos[] = $checkDetail['recieve_detail_id'];
        }

        $checkDetailInfos = DB::select()
            ->from('check_quality_details')
            ->where('recieve_detail_id', 'in', $recieveDetailInfos)
            ->execute('newerp')
            ->as_array('recieve_detail_id');
        $recieveInvoiceInfos = DB::select()
            ->from('recieve_invoices')
            ->where('id', 'in', array_unique($recieveInvoiceInfos))
            ->execute('newerp')
            ->as_array('id');
        $recieveDetailInfos = DB::select()
            ->from('recieve_details')
            ->where('id', 'in', $recieveDetailInfos)
            ->execute('newerp')
            ->as_array('id');

        foreach($_POST['checkQuanlityDetails'] as $checkDetail) {
            $recieveDetailId = $checkDetail['recieve_detail_id'];
            $recieveInvoiceId = $checkDetail['recieve_invoice_id'];
            if(!isset($checkDetailInfos[$recieveDetailId])) {
                if($recieveDetailInfos[$recieveDetailId]['skuchecksign'] == 10) {
                    $re[$checkDetail['rowNum']] = 6;
                    continue;
                }
                $sql = 'SELECT warehouseid,enterprise_dominant FROM purchaseorders WHERE id='.$recieveInvoiceInfos[$recieveInvoiceId]['purchaseorder_id'];
                $puinfo = DB::query(Database::SELECT,$sql)->execute('newerp')->as_array();
                $warehouse_id = $puinfo[0]['warehouseid'];
                $enterprise_dominant = $puinfo[0]['enterprise_dominant'];
                $checkArr = array();
                $checkArr['invoice_date']       = $checkTime;
                $checkArr['purchaseorder_id']   = $recieveInvoiceInfos[$recieveInvoiceId]['purchaseorder_id'];
                $checkArr['check_man']          = USER::Active_user()->id;
                $checkArr['supplier_id']        = $recieveInvoiceInfos[$recieveInvoiceId]['supplier'];
                $checkArr['recieve_detail_id']  = $recieveDetailId;
                $checkArr['warehouseid']        = $warehouse_id;
                $checkArr['enterprise_dominant']        = $enterprise_dominant;
                $checkArr['sku']                = $recieveDetailInfos[$recieveDetailId]['sku'];
                $checkArr['sku_name']           = $recieveDetailInfos[$recieveDetailId]['sku_name'];
                $checkArr['sku_standard']       = $recieveDetailInfos[$recieveDetailId]['sku_standard'];
                $checkArr['storage_position']   = $recieveDetailInfos[$recieveDetailId]['storage_position'];
                $checkArr['qualified_quantity'] = trim($checkDetail['ru_count']);
                $checkArr['check_quantity']     = trim($checkDetail['check_count']);
                $checkArr['store']              = trim($checkDetail['store']);
                $checkArr['batch_code']         = $recieveDetailInfos[$recieveDetailId]['batch_code'];
                $checkArr['export_tax_rebate']   = DB::select(array('export_tax_rebate'))
                                                    ->from('purchaseorders')
                                                    ->where('id','=',$checkArr['purchaseorder_id'])
                                                    ->get('export_tax_rebate');
                !empty($checkDetail['buhege_count']) && $checkArr['unquality_count'] = trim($checkDetail['buhege_count']);
                !empty($checkDetail['remark']) && $checkArr['remark'] = trim($checkDetail['remark']);

                /*0数据已保存过,1保存成功,2质检完成,3质检数量跟到货数据不对，请检查,4质检成功和入库成功,5质检失败，6待确认*/
                if($checkArr['check_quantity'] == $recieveDetailInfos[$recieveDetailId]['arrival_quantity']){
                    $sid = DB::insert('check_quality_details', array_keys($checkArr))
                        ->values($checkArr)
                        ->execute('newerp');

                    $checkDetailId = $sid['0'];

                    if($checkDetailId && $checkArr['qualified_quantity'] > 0){

                        $select_qcd = qcwo::selectreo($checkDetailId, 10);
                        $insert_wo  = qcwo::insert_wo($select_qcd);
                        $new_wo_ckdid=array();
                        foreach($select_qcd as $re){
                            $new_wo_ckdid[$re['check_quality_detail_id']]=$re['sku'];
                        }
                        //qcwo::updatesystemskucosts($new_wo_ckdid);
                        if($insert_wo){
                            $re[$checkDetail['rowNum']] = 4;
                        }else{
                            DB::delete('check_quality_details')
                                ->where('id', '=', $checkDetailId)
                                ->execute('newerp');
                            $checkDetailId = 0;
                            $re[$checkDetail['rowNum']] = 5;
                        }
                    } else {
                        $re[$checkDetail['rowNum']] = 2;
                    }
                } else {
                    $re[$checkDetail['rowNum']] = 3;
                }

                if($checkDetail['buhege_count'] > 0 && $checkDetailId > 0){
                    $unQualityArr                     = array();
                    $unQualityArr['invoice_date']     = $checkTime;
                    $unQualityArr['purchaseorder_id'] = $checkArr['purchaseorder_id'];
                    $unQualityArr['check_detail_id']  = $checkDetailId;
                    $unQualityArr['sku']              = $checkArr['sku'];
                    $unQualityArr['sku_name']         = $checkArr['sku_name'];
                    $unQualityArr['quality_man']      = USER::Active_user()->id;
                    $unQualityArr['sku_standard']     = $checkArr['sku_standard'];
                    $unQualityArr['quantity']         = trim($checkDetail['buhege_count']);
                    $unQualityArr['supplier']         = $checkArr['supplier_id'];
                    $unQualityArr['check_time']       = $checkTime;
                    $unQualityArr['store']            = $checkArr['store'];
                    $unQualityArr['warehouseid']      = $warehouse_id;
                    $unQualityArr['enterprise_dominant']      = $enterprise_dominant;
                    $unQualityArr['batch_code']       = $checkArr['batch_code'];
                    isset($checkArr['remark']) &&
                    $unQualityArr['quality_remark'] = $checkArr['remark'].',采购单质检不合格入不良品仓';

                    !empty($unQualityArr['purchaseorder_id']) &&
                    $unQualityArr['purchase_man'] = qualityaction::getpurchaseid($unQualityArr['purchaseorder_id']);


                    DB::insert('unqualified_deal_invoices',array_keys($unQualityArr))
                        ->values($unQualityArr) ->execute('newerp');
                }

                if($checkDetailId > 0){
                    DB::update('recieve_details')
                        ->set(array('check_count' => $checkArr['check_quantity']))
                        ->where('id', '=', $recieveDetailId)
                        ->execute('newerp');
                }

                if(!empty($checkArr['check_quantity']) &&
                    !empty($checkArr['purchaseorder_id']) &&
                    !empty($checkArr['sku']) &&
                    $recieveDetailId > 0
                ){
                    $set = "check_quantity = check_quantity + " . $checkArr['check_quantity'];
                    if(isset($unQualityArr['quantity']) && $unQualityArr['quantity'] > 0){
                        $set .= ', return_quantity = return_quantity + ' . $unQualityArr['quantity'];
                    }
                    $where     = "purchaseorder_id = " . $checkArr['purchaseorder_id']." AND sku='" . $checkArr['sku']."'";
                    $pur_query = "UPDATE purchaseorder_details SET " . $set." WHERE " . $where; //回写质检量和退回量给采购明细单
                    DB::query(Database::UPDATE,$pur_query)->execute('newerp');
                }
            } else {
                $re[$checkDetail['rowNum']] = 0;
            }
        }

        echo json_encode($re);
        exit;
    }


    //生成质检单和质检详细单，报损单
    public function Action_addcheck()
    {
        //增加质检日志
        if($_GET['arrid']&&$_GET['arrvalid']){
            //增加事务
            $instance=Database::instance('newerp');
            $instance->begin();
            $arrid    = trim($_GET['arrid']); //收货单id  recieve_invoice_id
            $arrvalid = trim($_GET['arrvalid']); //收货明细单号 recieve_details_id
            $arr      = DB::select()
                ->from('check_quality_details')
                ->where('recieve_detail_id','=',$arrvalid)
                ->execute('newerp')
                ->as_array();

            if(empty($arr)){
                $set = array();

                //查询出收货单信息
                $result = DB::select()
                    ->from('recieve_invoices')
                    ->where('id','=',$arrid)
                    ->execute('newerp')
                    ->as_array();

                $info = array();
                //查询出收货单明细信息
                $arr_info = DB::select()
                    ->from('recieve_details')
                    ->where('id','=',$arrvalid)
                    ->execute('newerp')
                    ->as_array();

                $sql = 'SELECT warehouseid,enterprise_dominant FROM purchaseorders WHERE id='.$result[0]['purchaseorder_id'];
                $puinfo = DB::query(Database::SELECT,$sql)->execute('newerp')->as_array();
                $warehouse_id = $puinfo[0]['warehouseid'];
                $enterprise_dominant = $puinfo[0]['enterprise_dominant'];
                $sql='SELECT quantity-ware_quantity num
                      FROM purchaseorder_details
                      WHERE purchaseorder_id='.$result[0]['purchaseorder_id'].'
                      AND sku="'.$arr_info[0]['sku'].'"';
                $wareAllowed=DB::query(Database::SELECT,$sql)->execute('newerp')->get('num');
                //@todo 产品要求开放多收商品质检入库
                /*if($wareAllowed<$_GET['ru_count']){
                    $instance->rollback();
                    echo 11;exit;
                }*/

                //添加质检明细单参数
                //$info['id']                 = rand(-999999999,-1);
                $info['invoice_date']       = date('Y-m-d H:i:s',time());
                $info['purchaseorder_id']   = $result['0']['purchaseorder_id'];
                $info['check_man']          = USER::Active_user()->id;
                $info['supplier_id']        = $result['0']['supplier'];
                $info['recieve_detail_id']  = $arrvalid;
                $info['warehouseid']        = $warehouse_id;
                $info['enterprise_dominant']        = $enterprise_dominant;
                $info['sku']                = $arr_info['0']['sku'];
                $info['sku_name']           = $arr_info['0']['sku_name'];
                $info['sku_standard']       = $arr_info['0']['sku_standard'];
                $info['storage_position']   = $arr_info['0']['storage_position'];
                $info['qualified_quantity'] = trim($_GET['ru_count']);
                $info['check_quantity']     = trim($_GET['check_count']);
                $info['store']              = trim($_GET['store']);
                $info['batch_code']         = $arr_info['0']['batch_code'];
                $info['export_tax_rebate']  = DB::select('export_tax_rebate')
                    ->from('purchaseorders')
                    ->where('id','=',$info['purchaseorder_id'])
                    ->execute('newerp')
                    ->get('export_tax_rebate');
                if(!empty($_GET['buhege_count'])){
                    $info['unquality_count'] = trim($_GET['buhege_count']);
                }

                if(!empty($_GET['remark'])){
                    $info['remark'] = trim($_GET['remark']);
                }

                if($info['check_quantity']==$arr_info['0']['arrival_quantity']){
                    $sid = DB::insert('check_quality_details',array_keys($info))
                        ->values($info)
                        ->execute('newerp');
                    
                    //增加质检日志
                    logs::purchaseorder_log($info['purchaseorder_id'], '质检，SKU：'.$info['sku'].'，数量：'.$info['check_quantity']);
                    if($sid['0']&&$info['qualified_quantity']>0){

                        $select_qcd = qcwo::selectreo($sid['0'],10);
                        $insert_wo  = qcwo::insert_wo($select_qcd);
                        if($insert_wo == 7){
                            echo $insert_wo;exit;
                        }
                        if($insert_wo){
                            $resMsg = 4;
                            logs::purchaseorder_log($info['purchaseorder_id'], '入库，SKU：'.$info['sku'].'，数量：'.$info['qualified_quantity']);
                        }else{
                            DB::delete('check_quality_details')
                                ->where('id','=',$sid['0'])
                                ->execute('newerp');
                            $sid['0'] = 0;
                            echo 5;
                            $instance->rollback();
                            exit;
                        }
                    }else{
                        $resMsg = 2;
                    }
                }else{
                    $resMsg = 3;
                }
                if($_GET['buhege_count']>0&&$sid['0']>0){
                    $cqid                          = $sid['0'];
                    $check_arr                     = array();
                    //$check_arr['id']               = rand(-999999999,-1);
                    $check_arr['invoice_date']     = date('Y-m-d H:i:s',time());
                    $check_arr['purchaseorder_id'] = $info['purchaseorder_id'];
                    $check_arr['check_detail_id']  = $cqid;
                    $check_arr['sku']              = $info['sku'];
                    $check_arr['sku_name']         = $info['sku_name'];
                    $check_arr['quality_man']      = USER::Active_user()->id;
                    $check_arr['sku_standard']     = $info['sku_standard'];
                    $check_arr['quantity']         = trim($_GET['buhege_count']);
                    $check_arr['supplier']         = $info['supplier_id'];
                    $check_arr['check_time']       = date('Y-m-d H:i:s',time());
                    $check_arr['store']            = $info['store'];
                    $check_arr['warehouseid']      = $warehouse_id;
                    $check_arr['enterprise_dominant']      = $enterprise_dominant;
                    
                    //$check_arr['batch_code']       = $info['batch_code'];
                    if(isset($info['remark'])){
                        $check_arr['quality_remark'] = $info['remark'].',采购单质检不合格入不良品仓';
                    }
                    if(!empty($check_arr['purchaseorder_id'])){
                        $check_arr['purchase_man'] = qualityaction::getpurchaseid($check_arr['purchaseorder_id']);
                    }

                    $uid = DB::insert('unqualified_deal_invoices',array_keys($check_arr))
                        ->values($check_arr)
                        ->execute('newerp');
                }
                if($sid['0']>0){
                    $up = array('check_count' => $info['check_quantity']);
                    DB::update('recieve_details')
                        ->set($up)
                        ->where('id','=',$arrvalid)
                        ->execute('newerp'); //将总质检量回写给收货单
                }

                if(!empty($info['check_quantity'])&&!empty($info['purchaseorder_id'])&&!empty($info['sku'])&&$sid['0']>0){

                    $set = "check_quantity = check_quantity + ".$info['check_quantity'];
                    if(isset($check_arr['quantity'])&&$check_arr['quantity']>0){
                        $set .= ',return_quantity=return_quantity + '.$check_arr['quantity'];
                    }
                    $where     = "purchaseorder_id = ".$info['purchaseorder_id']." AND sku='".$info['sku']."'";
                    $pur_query = "UPDATE purchaseorder_details SET ".$set." WHERE ".$where; //回写质检量和退回量给采购明细单
                    DB::query(Database::UPDATE,$pur_query)
                        ->execute('newerp');
                }
            }else{
                $resMsg = 0;
            }
            if(isset($resMsg)&&($resMsg==4 || $resMsg==2)){
                //$supplier = supplierskus::getSuppliers(array('name'), array('id' => "=" . $result[0]['supplier']));
                $check_quality_detail_id = $sid['0'];
                $sql = "SELECT id,warehouse_date,warehouse_quantity,type,single_price FROM warehouseorders WHERE check_quality_detail_id=$check_quality_detail_id ";
                $warehouse = DB::query(Database::SELECT,$sql)->execute('newerp')->as_array();
                $badType = !empty(trim($_GET['uids'])) && !empty(trim($_GET['buhege_count']))?$_GET['uids']:0;
                $badTypeName = '';
                if($badType){
                    $badTypeArr = explode(',',$badType);
                    foreach ($badTypeArr as $key => $value) {
                        $badTypeName [] = $this->fxCheckMsg[$value];
                    }
                    $badTypeName = implode(',',$badTypeName);
                }
                

                $msg =  array(
                     'recieve_detail_id' =>$arrvalid,
                     'logUniKey'     =>$warehouse[0]['id'],//'入库单ID'
                     'platSn'        =>'',//'留空（\'\'）',
                     'supplierId'    =>$result[0]['supplier'], //supplier_id
                     'unifiedSku'    =>$arr_info[0]['sku'], //sku 
                     'target'        =>$result[0]['purchaseorder_id'] ,//'预约单ID', purchaseorder_id
                     'recTime'       =>$result[0]['recieve_time'] ,//'到货时间（没有就写收货时间）', recieve_time
                     'wareTime'      =>$warehouse[0]['warehouse_date'],//'入库时间', check_time
                     'stockType'     =>'receipt',//类型(sales销量,invent盘点,refuse退货,receipt收货) 
                     'goodProStock'  =>$warehouse[0]['warehouse_quantity'],//'良品数', warehouse_quantity
                     'badProStock'   =>$_GET['buhege_count'],//'非良品数', unquality_count
                     'trackNo'       =>$result[0]['track_no'] ,//'追踪号', 
                     'price'         =>$warehouse[0]['single_price'],//'商品当前价格',  
                     'badProType'    =>$badType,//'不良品类型', 
                     'badTypeName'   =>$badTypeName,
                     'badProPicUrl'  =>'',//'不良品图片地址数组', []
                     'remark'        =>$info['remark'],//'不良品备注'
                );
                //echo json_encode($msg);exit;
                $res = $this->sendDataToFx($msg);
                $a = $res && json_decode($res,true)?json_decode($res,true):'';
                if($a){
                    $msg = array_merge($msg,array('res_status'=>$a['code'],'res_msg'=>$res));
                }else{
                    $msg = array_merge($msg,array('res_status'=>-1,'res_msg'=>$res));
                }
                
                DB::insert('check_quality_fx_msg',array_keys($msg))
                        ->values($msg)
                        ->execute('newerp');
                $instance->commit();
            }else{
                $instance->rollback();
            }
            echo $resMsg;
        }
        exit;
    }

    //分销只上接口
    public function sendDataToFx($msg){
        $json = json_encode($msg);
        $server_url = Kohana::$config->load('api_url');
        $fx_host = $server_url['fx_host'];
        $fx_key  = $server_url['fx_key'];
        $url = $fx_host.'/api/index.php?c=vmi&a=stockDetail&md5=';
        $get = array('c' => 'vmi', 'a' => 'stockDetail');
        $md5 = md5(join($get). $json . $fx_key);
        $url = $url.$md5;
        return Baseclass::invoke_curl_org($url,$json);
    }

    // 查询质检报告信息
    public function Action_qualityreport()
    {
        if(!ACL::check('qc print')) {
            Message::error('sorry，你没有权限进这个目录');
            $this->request->redirect(URL::base(TRUE));
        }
        if(count($_GET)<2){
            $this->title = __('打印质检报表');
            $view        = View::factory('quality/printquality');
            $result      = array();
            $view->bind('result',$result);
            $this->response->body($view);
        }else{
            $where      = qualityaction::qualitysql($_GET);
            $count      = qualityaction::qualitycount2($where);
            $pagination = Pagination::factory(array(
                'total_items'    => $count,
                //总记录数
                'items_per_page' => 20,
                //每页显示多少条
                'uri'            => $this->request->uri(),
            ));

            $limit  = $pagination->_offset.','.$pagination->items_per_page;
            $result = qualityaction::selectquality2($where,$limit,'invoice_date');
            if(empty($result)){
                Message::error('该条件查询不到相关数据！');
            }
            $this->title = __('查询质检报表');
            $view        = View::factory('quality/printquality');
            $view->bind('result',$result);
            foreach ($result as $k => $v) {
                foreach ($v as $key => $value) {
                    $users[] = $value['check_man'];
                }
                
            }
            $users = qualityaction::getQualitymen($users);
            $view->set('users',$users);
            $page_links       = $pagination->render();
            $view->page_links = $page_links;
            $view->set('getback',$_GET);
            $this->response->body($view);
        }
    }

    // 查询所有不合格产品信息
    public function Action_selectunquality()
    {
        if(empty($_GET)){
            $status      = qualityaction::getstatus();
            $this->title = __('不良品查询修改');
            $view        = View::factory('unqualified/selectunquality');
            $result      = array();
            $view->bind('status',$status);
            $view->bind('result',$result);
            $this->response->body($view);
        }else{

            if(!empty($_GET['checkid'])){
                $_GET['checkid'] = Erpuser::lookup_by_nick($_GET['checkid']);
                if($_GET['checkid']==''){
                    $_GET['checkid'] = 1;
                }
            }else{
                $_GET['checkid'] = '';
            }
            if(!empty($_GET['suppliername'])){
                $supplier = Newerpclientapi::getSuppliers($_GET['suppliername']);
                if($supplier){
                    $_GET['supplierid'] = $supplier[0]['id'];
                }else{
                    $_GET['supplierid'] = '-1';
                }

            }
            
            $status = qualityaction::getstatus();
            $st     = array();
            foreach($status as $key => $value){
                $st[$value['number']] = $value['value'];
            }

            $where      = qualityaction::unqualitysql($_GET);
            $count      = qualityaction::unqualitycount($where);
            $pagination = Pagination::factory(array(
                'total_items'    => $count,
                //总记录数
                'items_per_page' => 20,
                //每页显示多少条
                'uri'            => $this->request->uri(),
            ));
            $limit      = $pagination->_offset.','.$pagination->items_per_page;
            $result     = qualityaction::selecunqulity($where,$limit);
            $quality_men_id= array();
            foreach($result as $key => $value){
                $condtions = $value['supplier']?array('id' => '=' . $value['supplier']):'';
                $supplier_name = '';
                if(isset($_SESSION['supplier_name'][$value['supplier']])){
                    $supplier_name = $_SESSION['supplier_name'][$value['supplier']];
                }else{
                    if(!empty($condtions)){
                        $res = supplierskus::getSuppliers(array('name'), $condtions);
                    $_SESSION['supplier_name'][$value['supplier']] = $supplier_name = isset($res[0]['name'])?$res[0]['name']:'';
                    } 
                }
                $result[$key]['supplier'] = $supplier_name;
                $result[$key]['status']   = $st[$value['status']];
                $result[$key]['statusid'] = $value['status'];
                //$result[$key]['quality_man'] = qualityaction::getusername($value['quality_man']);
                $result[$key]['purchase_man'] = Erpuser::nick_by_id($value['purchase_man']);
                !empty($value['quality_man'])&&array_push($quality_men_id,$value['quality_man']);
            }
            !empty($quality_men_id)&&$quality_men=qualityaction::getQualitymen($quality_men_id);
            if(empty($result)){
                Message::error('该条件查询不到相关数据！');
            }
            $view        = View::factory('unqualified/selectunquality');
            foreach ($result as $k => $v) {
                foreach ($v as $key => $value) {
                    $users[] = $value['check_man'];
                }
                
            }
            $users = qualityaction::getQualitymen($users);
            $view->set('users',$users);
            $this->title = __('查询不良品信息');
           
            $view->bind('status',$status);
            $view->bind('result',$result);
            $view->set('getback',$_GET);
            isset($quality_men)&&$view->set('quality_men',$quality_men);
            $page_links       = $pagination->render();
            $view->page_links = $page_links;
            $this->response->body($view);
        }
    }

    //sku详情信息
    public function Action_getSkuInfo(){
        $sku = $_POST['sku'];
        $sku_info = Skusystemapi::getSkuInfoByBase($sku);
        if(!empty($sku_info[0]) && empty($sku_info[0]['unit'])){
            $sql = "SELECT nuit FROM vmi_supplier_skus WHERE sku='$sku'";
            $unit = DB::query(Database::SELECT,$sql)->execute('newerp')->get('nuit');
            $sku_info[0]['unit'] = $unit?$unit:'';
        }
        echo json_encode($sku_info[0]);
        exit;
    }

    // 手动录入不良品信息
    public function Action_addunquality()
    {
        if(!empty($_POST['sku'])){
            $sku = qualityaction::getskuname($_POST['sku']);
            if(!empty($sku)){
                $id = qualityaction::insertunquality($_POST);
                if($id){

                    Message::success('添加成功！');
                }else{

                    Message::error('添加失败！');
                }
            }else{
                Message::error('SKU不存在，无法添加！');
            }
        }

        $this->title = __('录入质检不合格产品');
        $view        = View::factory('unqualified/manualproducts');
        $view->set('user',User::active_user());
        $this->response->body($view);
    }


    // 修改不良品界面
    public function Action_editbadproducts()
    {
        $id = trim($_GET['id']);
        if($id){

            $purchaseid  = trim($_GET['purchaseid']);
            $info        = qualityaction::selone($id);
            $this->title = __('修改不良品信息');
            $view        = View::factory('unqualified/editmanualproducts');
            $view->bind('info',$info);
            $view->bind('id',$id);
            $view->bind('purchaseid',$purchaseid);
            $this->response->body($view);
        }
    }

    // 修改不良品
    public function Action_updatebadproduct()
    {
        $id = trim($_POST['id']);
        //print_r($_POST);exit;
        $where   = 'id = '.$id;
        $table   = 'unqualified_deal_invoices';
        $quality = intval(trim($_POST['sku_quality']));
        $remarks = addslashes(trim($_POST['remarks']));
        $set     = 'quantity='.$quality.',quality_remark=\''.$remarks.'\'';
        $uid     = qualityaction::updatequality($set,$where,$table);
        if(!empty($uid)){
            $data               = array();
            $data['sku']        = trim($_POST['sku']);
            $data['value']      = '修改不良品信息';
            $data['userid']     = USER::Active_user()->id;
            $data['type']       = 'update';
            $data['controller'] = 'quality';
            $data['action']     = 'updatebadproduct';
            $data['table_name'] = $table;
            $data['table_id']   = $id;
            qualityaction::insertlog($data);
        }
        $this->request->redirect('quality/selectunquality?id='.$id);
    }

    // 手动不良品出库
    public function Action_adddelivery()
    {

        $this->title = __('录入不良品出库记录');
        $view        = View::factory('unqualified/warehouseproducts');
        $this->response->body($view);
    }

    //下载报表
    public function action_download()
    {
        set_time_limit(0);
        ini_set('memory_limit','500M');

        if(!empty($_GET['checkid'])){
            $_GET['checkid'] = Erpuser::lookup_by_nick($_GET['checkid']);
            if($_GET['checkid']==''){
                $_GET['checkid'] = 1;
            }
        }else{
            $_GET['checkid'] = '';
        }
        if(!empty($_GET['suppliername'])){
                $supplier = Newerpclientapi::getSuppliers($_GET['suppliername']);
                if($supplier){
                    $_GET['supplierid'] = $supplier[0]['id'];
                }else{
                    $_GET['supplierid'] = '-1';
                }

        }
        
        $status = qualityaction::getstatus();
        $st     = array();
        foreach($status as $key => $value){
            $st[$value['number']] = $value['value'];
        }

        $where  = qualityaction::unqualitysql($_GET);
        $count  = qualityaction::unqualitycount($where);
        $result = qualityaction::selecunqulity($where);
        $quality_men_id=array();

        foreach($result as $key => $value){
            $result[$key]['supplier'] = !empty(qualityaction::getsuppliername($value['supplier']))?qualityaction::getsuppliername($value['supplier']):'';
            $result[$key]['status']   = $st[$value['status']];
            $result[$key]['statusid'] = $value['status'];
            //$result[$key]['quality_man'] = qualityaction::getusername($value['quality_man']);
            $result[$key]['purchase_man'] = Erpuser::nick_by_id($value['purchase_man']);
            !empty($value['quality_man'])&&array_push($quality_men_id,$value['quality_man']);
        }
        $quality_men=qualityaction::getQualitymen($quality_men_id);
        require_once(Kohana::find_file('vendor','PHPExcel/PHPExcel/IOFactory'));
        $this->objReader = PHPExcel_IOFactory::createReader('Excel5');
        $objPHPExcel     = new PHPExcel();
        $objPHPExcel->getProperties()
            ->setCreator("YKS")
            ->setLastModifiedBy("YKS")
            ->setTitle("Office 2003 XLSX Test Document")
            ->setSubject("Office 2003 XLSX Test Document")
            ->setDescription("Test document for Office 2003 XLSX, generated using PHP classes.")
            ->setKeywords("office 2003 openxml php")
            ->setCategory("Test result file");
        //单号 	VMI预约单号 	质检单号 	SKU 	中文名称 	供应商 	不合格量 	质检时间 	计划员 	质检不合格原因 	状态 	操作
        $objActSheet = $objPHPExcel->setActiveSheetIndex(0);
        $objActSheet->setCellValue('A1','单号');
        $objActSheet->setCellValue('B1','VMI预约单号');
        $objActSheet->setCellValue('C1','质检单号');
        $objActSheet->setCellValue('D1','SKU');
        $objActSheet->setCellValue('E1','中文名称');
        $objActSheet->setCellValue('F1','供应商');
        $objActSheet->setCellValue('G1','不合格量');
        $objActSheet->setCellValue('H1','质检时间');
        $objActSheet->setCellValue('I1','计划员');
        $objActSheet->setCellValue('J1','质检不合格原因');
        $objActSheet->setCellValue('K1','质检员');
        $objActSheet->setCellValue('L1','状态');

        $num = 2;
        foreach($result as $value){
            $objActSheet->setCellValue('A'.$num,$value['id']);
            $objActSheet->setCellValue('B'.$num,$value['purchaseorder_id']);
            $objActSheet->setCellValue('C'.$num,$value['check_detail_id']);
            $objActSheet->setCellValue('D'.$num,$value['sku']);
            $objActSheet->setCellValue('E'.$num,$value['sku_name']);
            $objActSheet->setCellValue('F'.$num,$value['supplier']);
            $objActSheet->setCellValue('G'.$num,$value['quantity']);
            $objActSheet->setCellValue('H'.$num,$value['check_time']);
            $objActSheet->setCellValue('I'.$num,$value['purchase_man']);
            $objActSheet->setCellValue('J'.$num,$value['quality_remark']);
            $objActSheet->setCellValue('K'.$num,$quality_men[$value['quality_man']]);
            $objActSheet->setCellValue('L'.$num,$value['status']);
            $num++;
        }
        $objPHPExcel->getActiveSheet()
            ->setTitle('不良品查询修改报表');
        $objPHPExcel->setActiveSheetIndex(0);
        $day      = date("m-d");
        $filename = $day.'不良品查询修改报表'.'.xls';
        ob_end_clean();
        header("Content-Type: application/vnd.ms-excel; charset=utf-8");
        header('Content-Disposition: attachment;filename='.$filename);
        header('Cache-Control: max-age=0');
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel,'Excel5');
        $objWriter->save('php://output');
        exit;
    }

    public function action_getBatchCode() {
        $warehouse_id = Kohana::$config->get('warehouse')->warehouse_id;
        $results = array();
        if($warehouse_id && !empty($_GET['term'])){
            $sql = 'SELECT
                `batch_code`
            FROM `batches`
            WHERE `batch_code` LIKE \'' . $warehouse_id . '%' . $_GET['term'] . '\'
            ORDER BY `id` DESC
            LIMIT 5';

            $batch_codes = DB::query(Database::SELECT, $sql)->execute('newerp')->as_array(NULL, 'batch_code');
            if(!empty($batch_codes))
            {
                foreach($batch_codes as $batch_code){
                    $results[] = array(
                        'label' => $batch_code,
                        'name'  => $batch_code
                    );
                }
            }
        }

        echo json_encode($results);
        exit;
    }
}